package com.cjh.controller;

import com.cjh.entity.User;
import com.cjh.execption.InsertException;
import com.cjh.service.IUserService;
import com.cjh.service.impl.UserServiceImpl;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@Api(tags = "用户控制器")
public class UserController {

    @Autowired
    IUserService userService;

    @ApiOperation("/sayhello")
    @RequestMapping(value = "/toHelloworld",method = RequestMethod.GET)
    public String helloWorld(){
        return "index";
    }

    @ApiOperation("/hello")
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    @ResponseBody
    public String hello(){
        return "世界";
    }

    @ApiOperation("删除用户")
    @DeleteMapping(value = "/user/{id}")
    @ResponseBody
    public ResponseEntity<String> deleteByPrimaryKey(@PathVariable("id") int id) {
        userService.deleteByPrimaryKey(id);
        return ResponseEntity.ok("成功");
    }

    @ApiOperation("增加用户")
    @PostMapping(value = "/user")
    @ResponseBody
    public ResponseEntity<User> insert(User record) throws InsertException {
        User user = new User();
        user.setName(record.getName());
        user.setEmail(record.getEmail());
        user.setPhone(record.getPhone());
        user.setCreatetime(new Date());
        User insertUser = null;
        try {
             insertUser = userService.insert(user);
        }catch (RuntimeException e){
            throw new InsertException("插入失败");
        }
        return ResponseEntity.ok(insertUser);
    }

    @ApiOperation("查询用户")
    @GetMapping(value = "/user/{id}")
    @ResponseBody
    public ResponseEntity<User> selectByPrimaryKey(@PathVariable("id")int id) {
        userService.selectByPrimaryKey(id);
        return ResponseEntity.ok(userService.selectByPrimaryKey(id));
    }

    @ApiOperation("分页查询")
    @GetMapping(value = "/user/list/{page}")
    @ResponseBody
    public ResponseEntity<PageInfo<User>> selectListByPage(@PathVariable("page")int page) {
        return ResponseEntity.ok(userService.selectListByPage(page));
    }


    @ApiOperation("更新用户")
    @PutMapping(value = "/user")
    @ResponseBody
    public void updateByPrimaryKey(User record) {
        User user = userService.selectByPrimaryKey(record.getId());
        user.setName(record.getName());
        user.setEmail(record.getEmail());
        user.setPhone(record.getPhone());
        userService.updateByPrimaryKey(user);
    }

}
